package com.example.aircraftticketingsystemserver.controller;

import com.example.aircraftticketingsystemserver.entity.DatabaseDTO;
import com.example.aircraftticketingsystemserver.utils.Result;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@CrossOrigin(origins = {"*","null"})
@RequestMapping("/database")
public class DatabaseController {
    /**
     * 数据库备份
     */
    @GetMapping("backup")
    public Result backup() throws IOException {
        Runtime runtime = Runtime.getRuntime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        // 获取当前日期时间
        Date now = new Date();
        // 格式化日期时间为字符串
        String formattedDate = sdf.format(now)+"FlightDB.sql";
        runtime.exec("\"C:/Program Files/MySQL/MySQL Server 8.0/bin/mysqldump.exe\" -uroot -p040825 --databases aircraft-ticketing-system -r D:/学习资料/数据库系统/数据库课设/飞机票售票系统/数据库备份/"+formattedDate);
        return Result.ok();
    }


    @GetMapping("getAllDbScript")
    public Result getAllDbScript() {
        File dir = new File("D:/学习资料/数据库系统/数据库课设/飞机票售票系统/数据库备份/");
        List<String> sqlFiles = new ArrayList<>();
        AtomicInteger idGenerator = new AtomicInteger(1); // 用于生成唯一的ID

        // 遍历目录并收集所有.sql文件
        try {
            Files.walk(Paths.get(dir.getAbsolutePath()))
                    .filter(path -> Files.isRegularFile(path) && path.toString().endsWith(".sql"))
                    .forEach(path -> sqlFiles.add(path.getFileName().toString()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取SQL脚本失败：" + e.getMessage());
        }

        List<DatabaseDTO> resultVoList = sqlFiles.stream()
                .map(fileName -> {
                    DatabaseDTO obj = new DatabaseDTO();
                    obj.setName(fileName); // 设置文件名作为name
                    Long ID = (long)idGenerator.getAndIncrement();
                    obj.setId(ID); // 使用递增的计数器作为ID
                    return obj;
                })
                .collect(Collectors.toList());

        return Result.ok(resultVoList);
    }

    @GetMapping("getNewDb")
    public Result getNewDB(@RequestParam String scriptName) throws IOException, InterruptedException {

        // 拼接完整的命令
        String command = "\"C:/Program Files/MySQL/MySQL Server 8.0/bin/mysql.exe\" -uroot -p040825 aircraft-ticketing-system < D:/学习资料/数据库系统/数据库课设/飞机票售票系统/数据库备份/" + scriptName;
        // 创建 ProcessBuilder 实例
        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", command);
        pb.redirectErrorStream(true); // 合并错误流和标准输出
        // 启动进程
        Process process = pb.start();
        // 读取输出流
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        // 等待进程结束并检查退出代码
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new IOException("恢复数据库的过程失败 " + exitCode);
        }

        return Result.ok("数据库恢复成功");
    }
}
